import { stringify } from '@angular/compiler/src/util';
import { Component, OnInit, NgModule } from '@angular/core';
import { NzModalService } from 'ng-zorro-antd/modal';
@Component({
    selector: 'tic-tac-toe',
    templateUrl: './tic-tac-toe.component.html',
    styleUrls: ['./tic-tac-toe.component.scss']
})

export class TicTacToeComponent implements OnInit {
    board: Array<number>;
    chessBoard: Array<number>;
    turn = true;
    chessNum = 0;
    winFlag = false;
    constructor(private modal: NzModalService) {

    }

    ngOnInit() {
        this.board = new Array(9);
        this.chessBoard = new Array(9);
    }

    putChess(e) {
        const target = e.target;
        if (target.innerHTML === "") {
            if (this.turn) {
                target.innerHTML = "x";
                this.chessBoard[target.id] = 1;
                this.check(1);
            } else {
                target.innerHTML = "o";
                this.chessBoard[target.id] = 2;
                this.check(2);
            }
            this.turn = !this.turn;
            this.chessNum += 1;
        }

    }

    check(chess:any) {

        if ((this.chessBoard[0] == chess && this.chessBoard[1] === chess && this.chessBoard[2] === chess)
            ||
            (this.chessBoard[3] === chess && this.chessBoard[4] === chess && this.chessBoard[5] === chess)
            ||
            (this.chessBoard[6] === chess && this.chessBoard[7] === chess && this.chessBoard[8] === chess)
            ||
            (this.chessBoard[2] === chess && this.chessBoard[4] === chess && this.chessBoard[6] === chess)
            ||
            (this.chessBoard[0] === chess && this.chessBoard[3] === chess && this.chessBoard[6] === chess)
            ||
            (this.chessBoard[0] === chess && this.chessBoard[4] === chess && this.chessBoard[8] === chess)
            ||
            (this.chessBoard[1] === chess && this.chessBoard[4] === chess && this.chessBoard[7] === chess)
            ||
            (this.chessBoard[2] === chess && this.chessBoard[5] === chess && this.chessBoard[8] === chess)
        ) {
            console.log(chess + " win!");
            this.winFlag = true;
            this.modal.success({
                nzTitle: "Player " + chess + " win!",
                nzContent: "Player " + chess + " win this round!",
                nzOnOk: () => { this.resetChessBoard(); }
            });

        }

        if (this.chessNum >= 8 && !this.winFlag) {
            this.modal.success({
                nzTitle: "Nobody win!",
                nzContent: "Tie this round!",
                nzOnOk: () => { this.resetChessBoard(); }
            });
        }

    }

    resetChessBoard() {
        for (let i = 0; i < this.chessBoard.length; i++) {
            this.chessBoard[i] = 0;
            document.getElementById(String(i)).innerHTML = "";
        }
        this.chessNum = 0;
        this.winFlag = false;
    }
}